package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.query.TravelCondition;
import cn.wolfcode.luowowo.query.TravelQuery;
import cn.wolfcode.luowowo.repository.TravelRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.ITravelService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repository;

    @Override
    public Travel get(String id) {
        Optional<Travel> optional = repository.findById(id);
        //如果数据库不是空的
        if (optional.isPresent()) {
            Travel travel = optional.get();
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            travel.setAuthor(userInfo);
            travel.setDest(destinationService.get(travel.getDestId()));
            return  travel;
        }
        return null;
    }

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;
    /**
     * 分页操作
     *
     * @param qo 分页条件
     * @return
     */
    @Override
    public Page list(TravelQuery qo) {
        Query query = new Query();
        //指定城市模块的条件查询 参数destId
        if (qo.getState() != -1){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }
        if (qo.getDestId()!= null) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        TravelCondition day = qo.getDayType();
        TravelCondition perExpend = qo.getPerExpendType();
        //出行天数的转换和条件查询
        if (day != null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        //人均花费的转换和条件查询
        if (perExpend != null){
            query.addCriteria(Criteria.where("perExpend").gte(perExpend.getMin()).lte(perExpend.getMax()));
        }
        //排序是最新的或者是最热的
        if (qo.getOrderType() == 2){
            qo.setPageable(PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize()
                    , Sort.Direction.DESC,"viewnum"));
        }else {
            qo.setPageable(PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize()
                    , Sort.Direction.DESC,"createTime"));
        }
        //等于2的话就是后端操作
        //限制查询的条件  要同时满足 公共状态  和  发布   状态
        if (qo.getCondition() == 2){
            query.addCriteria(new Criteria().andOperator(
                    new Criteria().where("isPublic").is(Travel.ISPUBLIC_YES),
                    new Criteria().where("state").is(Travel.STATE_RELEASE)
            ));
        }
        Page<Travel> page = DBHelper.query(template, Travel.class, query, qo.getPageable());
        //设置用户的信息
        for (Travel travel : page.getContent()) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return page;
    }
     @Autowired
     private IDestinationService destinationService;
    @Override
    public String saveOrUpdate(Travel travel) {
        //添加或者更新时,需要准备的内容
        //1.目的地名称
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDest(destination);
        travel.setDestName(destination.getName());
        //3.创建时间/发布时间/最后更新时间
         travel.setLastUpdateTime(new Date());
        if (!StringUtils.hasLength(travel.getId())) {
            travel.setId(null);
            travel.setCreateTime(new Date());
            repository.save(travel);
        } else {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(travel.getId()));
            DBHelper.update(template, query, travel, "destId", "destName", "userId", "title",
                    "coverUrl", "travelTime","perExpend","day","person","lastUpdateTime","isPublic");
        }
        return travel.getId();
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot", hot);
        template.updateMulti(query, update, Travel.class);
    }

    @Override
    public void changeState(String id, int state) {
        //查不到这个游记的话
        if (this.get(id) == null) {
            throw new RuntimeException("参数异常");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        Travel travel = this.get(id);
        travel.setLastUpdateTime(new Date());
        //如果是待发布/发布之后更新时间
        if (state == Travel.STATE_RELEASE) {
            travel.setState(state);
            travel.setLastUpdateTime(new Date());
        } else{//已发布  拒绝之后更新时间  设置发布时间为null
            travel.setState(Travel.STATE_REJECT);
            travel.setReleaseTime(null);
        }
        DBHelper.update(template,query,travel,"state","lastUpdateTime","releaseTime");
    }

    @Override
    public String getContentById(String id) {
        String contentById = repository.findContentById(id);
        return contentById;
    }

    @Override
    public List<Travel> findByDestIdForTravel(String destId) {
        //查询点击前三的攻略
        PageRequest of = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Travel> byDestId = repository.findByDestId(destId,of);
        return byDestId;
    }

    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public List<Travel> getByDestName(String keyword) {
        List<Travel> byDestName = repository.findByDestName(keyword);
        for (Travel travel : byDestName) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return byDestName;
    }
}
